/**
 * 后台接口文件
 */
import requestApi from 'ssccommon/components/requestApi';
import { ajax } from 'nc-lightapp-front';
import { toast } from 'nc-lightapp-front';
import getDefDataFromMeta from 'ssccommon/utils/getDefDataFromMeta';
import { viewModel } from 'nc-lightapp-front';
import attachments from 'uap/common/components/getAttachmentInfo';
import _ from 'lodash-es';
// import presetVar from "./presetVar";
const presetVar = window.presetVar;
const { getAttachments, getAttachmentsInfo } = attachments;
let { getGlobalStorage } = viewModel;

let pageCode = window.presetVar.pageCode;
let requestDomain = '';
let requestApiOverwrite = {
    ...requestApi,
    //单据模板接口
    tpl: opt => {
        let domain = ''; //'https://mock.yonyoucloud.com/mock/172';
        ajax({
            url: opt.url || `${domain}/nccloud/erm/erbudgetmg/FysqTempletAction.do`,
            data: opt.data,
            success: opt.success
        });
    },
    query: opt => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqViewBillAction.do`,
            data: opt.data,
            success: data => {
                if (data.data && data.data.userjson) {
                    window.presetVar.noamount = JSON.parse(data.data.userjson).noamount; //无金额申请-控制项   false or true
                    window.presetVar.canChange = JSON.parse(data.data.userjson).canChange || false; //是否可变更
                    window.presetVar.linkHis = JSON.parse(data.data.userjson).linkHis || false; //是否可联查变更历史,用于显示按钮控制
                }
                opt.success(data);
            }
        });
    },
    save: opt => {
        //数据适配开始
        adptBodyData(opt.data.head[presetVar.head.head1].rows, opt.data.bodys);

        //数据适配结束
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            uistate: opt.status,
            tradetype: window.presetVar.billtype,
            ntbCheck: window.ntbCheck,
            accessorybillid: opt.accessorybillid,
            fromssc: 'N',
            msg_pk_bill: null,
            userjson: "{'pagecode':'" + pageCode + "','appcode':'" + window.presetVar.appCode + "'}"
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqSaveBillAction.do`,
            data: opt.data,
            success: data => {
                if (data.data && data.data.userjson) {
                    window.presetVar.noamount = JSON.parse(data.data.userjson).noamount; //无金额申请-控制项   false or true
                    window.presetVar.canChange = JSON.parse(data.data.userjson).canChange || false; //是否可变更
                    window.presetVar.linkHis = JSON.parse(data.data.userjson).linkHis || false; //是否可联查变更历史,用于显示按钮控制
                }
                opt.success(data);
                window.ntbCheck = 'false';
            }
        });
    },
    billInvalid: opt => {
        //数据适配开始
        adptBodyData(opt.data.head[presetVar.head.head1].rows, opt.data.bodys);

        //数据适配结束
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            tradetype: window.presetVar.billtype,
            userjson: "{'pagecode':'" + pageCode + "'}"
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqInvalidBillAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
            }
        });
    },
    billEnable: opt => {
        //数据适配开始
        adptBodyData(opt.data.head[presetVar.head.head1].rows, opt.data.bodys);

        //数据适配结束
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            tradetype: window.presetVar.billtype,
            userjson: "{'pagecode':'" + pageCode + "'}"
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqRestartBillAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
            }
        });
    },
    billClose: opt => {
        //数据适配开始
        adptBodyData(opt.data.head[presetVar.head.head1].rows, opt.data.bodys);

        opt.data.pageid = pageCode;
        //数据适配结束
        opt.data = {
            ...opt.data,
            tradetype: window.presetVar.billtype,
            userjson: "{'pagecode':'" + pageCode + "'}"
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqCloseBillAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
            }
        });
    },
    billRemove: opt => {
        //数据适配开始
        let openbillid = '';
        opt.data.head[presetVar.head.head1].rows.map(row => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    if (key === 'pk_mtapp_bill') openbillid = row.values[key].value;
                }
            }
            return row;
        });
        //数据适配结束
        opt.data = {
            ...opt.data,
            openbillid: openbillid
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqDeleteBillAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
            }
        });
    },
    loadData: opt => {
        //数据适配开始
        let reqData = {
            uistate: 'add',
            tradetype: window.presetVar.billtype,
            head: {}
        };

        reqData = {
            ...reqData,
            ...genReqParamForLoadData(opt.meta)
        };
        let props = opt.props;
        //数据适配结束
        reqData.nodecode = '2611_IWEB';
        reqData.userjson =
            "{'pagecode':'" +
            pageCode +
            "','appcode':'" +
            window.presetVar.appCode +
            "','templateid':'" +
            (opt.meta || {}).pageid +
            "'}";
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqDefDataAction.do`,
            data: reqData,
            success: data => {
                //数据适配开
                if (isJSON(JSON.parse(data.data.userjson).reimsrc))
                    window.presetVar.reimsrc = JSON.parse(JSON.parse(data.data.userjson).reimsrc); //核心控制项-影响因素

                window.presetVar.reimruleitemkeys = JSON.parse(data.data.userjson).reimruleitemkeys; //报销标准涉及字段
                window.presetVar.showitemkey = JSON.parse(data.data.userjson).showitemkey; //显示项
                window.presetVar.noamount = JSON.parse(data.data.userjson).noamount; //无金额申请-控制项   false or true
                window.presetVar.ratecontorl = JSON.parse(data.data.userjson).RATECONTORL; //集团参数NC004“组织汇率是否可编辑
                window.presetVar.zzbwb = JSON.parse(data.data.userjson).ZZBWB; //组织币种

                let numberInitialvalueField = ['global_currinfo', 'group_currinfo', 'org_currinfo', 'rowno'];

                const bodyKeys = Object.keys(data.data.bodys);
                bodyKeys.forEach(bodyKey => {
                    opt.meta[bodyKey].items.forEach((item, index) => {
                        let bodyValues = data.data.bodys[bodyKey].rows[0].values;
                        let attrcode = item.attrcode;
                        if (bodyValues[attrcode]) {
                            if (item.itemtype != 'number' || numberInitialvalueField.indexOf(item.attrcode) >= 0) {
                                item.initialvalue = {
                                    value: bodyValues[attrcode].value,
                                    display: (bodyValues[attrcode].display = null
                                        ? bodyValues[attrcode].value
                                        : bodyValues[attrcode].display)
                                };
                            }
                        }
                        //处理交叉校验规则和参照过滤
                        filterAllRefParm(item, props, bodyKey);
                    });
                });

                let headValues = data.data.head[presetVar.head.head1].rows[0].values;
                window.presetVar.headValuesAll = headValues;

                opt.meta[presetVar.head.head1].items.forEach(item => {
                    let attrcode = item.attrcode;
                    if (headValues[attrcode]) {
                        item.initialvalue = {
                            value: headValues[attrcode].value,
                            scale: headValues[attrcode].scale,
                            display: (headValues[attrcode].display = null
                                ? headValues[attrcode].value
                                : headValues[attrcode].display)
                        };
                        //处理交叉校验规则和参照过滤
                        filterAllRefParm(item, props, presetVar.head.head1);
                    }
                });
                //适配多表头
                if (opt.meta.formrelation) {
                    opt.meta.formrelation[presetVar.head.head1].forEach(item => {
                        if (opt.meta[item]) {
                            opt.meta[item].items.forEach(key => {
                                let attrcode = key.attrcode;
                                if (headValues[attrcode]) {
                                    key.initialvalue = {
                                        value: headValues[attrcode].value,
                                        scale: headValues[attrcode].scale,
                                        display: (headValues[attrcode].display = null
                                            ? headValues[attrcode].value
                                            : headValues[attrcode].display)
                                    };
                                    //处理交叉校验规则和参照过滤
                                    filterAllRefParm(key, props, presetVar.head.head1);
                                }
                            });
                        }
                    });
                }
                opt.success(opt.meta, data.data);
            }
        });
    },

    changeByHead: opt => {
        opt.data = {
            ...opt.data,
            // userjson: "{'pagecode':'" + pageCode + "','appcode':'" + window.presetVar.appCode +  "','templateid':'" + opt.data.templateid + "'}"
            userjson: JSON.stringify({
                pagecode: pageCode,
                appcode: window.presetVar.appCode,
                templateid: opt.data.templateid,
                tableid: opt.data.tableid
            })
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqValueChangedAction.do`,
            data: opt.data,
            async: false,
            success: data => {
                opt.success(data);
            }
        });
    },
    changeByBody: opt => {
        opt.data = {
            ...opt.data,
            // userjson: "{'pagecode':'" + pageCode + "','appcode':'" + window.presetVar.appCode + "','checkrule':'" + opt.data.checkrule + "','templateid':'" + opt.data.templateid + "'}"
            userjson: JSON.stringify({
                pagecode: pageCode,
                appcode: window.presetVar.appCode,
                checkrule: opt.data.checkrule,
                templateid: opt.data.templateid,
                tableid: opt.data.tableid
            })
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqValueChangedAction.do`,
            data: opt.data,
            async: false,
            success: data => {
                opt.success(data);
            }
        });
    },
    copy: opt => {
        //单据复制
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            userjson: "{'pagecode':'" + pageCode + "'}"
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqCopyBillAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
            }
        });
    },
    change: opt => {
        //变更
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            userjson: "{'pagecode':'" + pageCode + "'}"
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqForChangeDefDataAction.do`,
            data: opt.data,
            success: data => {
                if (data.data.userjson) {
                    window.change_accessorybillid = JSON.parse(data.data.userjson).accessorybillid || '';
                }
                opt.success(data);
            }
        });
    },
    billSubmit: opt => {
        let openbillid = "''";
        opt.data.head[presetVar.head.head1].rows.map(row => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    if (key === 'pk_mtapp_bill') openbillid = row.values[key].value;
                }
            }
            return row;
        });
        if (opt.assignBillId) {
            openbillid = opt.assignBillId;
        }
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            accessorybillid: opt.accessorybillid,
            userjson:
                "{'pagecode':'" +
                pageCode +
                "','appcode':'" +
                window.presetVar.appCode +
                "'" +
                ",'openbillid':" +
                openbillid +
                ",'tradetype':'" +
                window.presetVar.billtype +
                "'" +
                ",'ntbCheck':'" +
                window.ntbCheck +
                "'" +
                ",'fromssc':'N'" +
                ",'uistate':" +
                opt.status +
                ",'assingUsers':" +
                JSON.stringify(window.assingUsers) +
                ",'accessorybillid':" +
                JSON.stringify(opt.accessorybillid) +
                '}'
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqSubmitAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
                window.ntbCheck = 'false';
            },
            error: data => {
                toast({ content: data.message, color: 'danger' });
                opt.error(data);
            }
        });
    },
    billRecall: opt => {
        let openbillid = '';
        opt.data.head[presetVar.head.head1].rows.map(row => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    if (key === 'pk_mtapp_bill') openbillid = row.values[key].value;
                }
            }
            return row;
        });
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            userjson: "{'pagecode':'" + pageCode + "','openbillid':'" + openbillid + "'}"
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqRecallAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
            },
            error: data => {
                toast({ content: data.message, color: 'danger' });
            }
        });
    },
    billView: opt => {
        let openbillid = '';
        let pk_tradetype = '';
        opt.data.head[presetVar.head.head1].rows.map(row => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    if (key === 'pk_mtapp_bill') {
                        openbillid = row.values[key].value;
                    }
                    if (key === 'pk_tradetype') {
                        pk_tradetype = row.values[key].value;
                    }
                }
            }
            return row;
        });
        opt.data.pageid = pageCode;
        opt.data = {
            ...opt.data,
            userjson:
                "{'pagecode':'linkjkbx_list'" +
                ",'openbillid':'" +
                openbillid +
                "'" +
                ",'pk_tradetype':'" +
                pk_tradetype +
                "'" +
                '}'
        };
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/erbudgetmg/FysqLinkQueryAction.do`,
            data: opt.data,
            success: data => {
                opt.success(data);
            },
            error: data => {
                toast({ content: data.message, color: 'danger' });
            }
        });
    },
    handleLoadDataResDada: (meta, data) => {
        handleLoadDataResDada(meta, data);
    },
    generatBillId: opt => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/action/generatBillId.do`,
            data: opt.data,
            success: data => {
                data = data.data;
                opt.success(data);
            },
            error: data => {
                toast({ content: data.message, color: 'danger' });
            }
        });
    },
    getUnEditAttributes: opt => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/pub/ErmAttributeEditableAction.do`,
            data: opt.data,
            success: data => {
                data = data.data;
                opt.success(data);
            },
            error: data => {
                toast({ content: data.message, color: 'warning' });
            }
        });
    },
    /**
     * 获取控制附件修改和必须上传的接口
     */
    getAttachmentControlParams: opt => {
        ajax({
            url: opt.url || `${requestDomain}/nccloud/erm/ermextendattr/ErmAccessoryControl.do`,
            data: opt.data,
            success: response => {
                const data = response.data;
                if (data && data.success) {
                    opt.success(data);
                } else {
                    toast({ content: data.message, color: 'danger' });
                }
            },
            error: data => {
                toast({ content: data.message, color: 'danger' });
            }
        });
    },

    /**
     * 判断附件是否已经上传
     */
    isAttachmentsUploaded: async billId => {
        const count = await getAttachments(billId);
        return count > 0;
    }
};

async function isUploadedAttachments(props) {
    const billId = props.getUrlParam('billid') || props.getUrlParam('id') || this.state.billId || '';
    //附件控制必传
    if (window.presetVar.attachmentControl && window.presetVar.attachmentControl.necessary) {
        if (!billId) {
            toast({ content: '必须上传附件', color: 'danger' });
            return false;
        }
        const hasUploaded = await requestApiOverwrite.isAttachmentsUploaded(billId);
        if (hasUploaded) {
            return true;
        } else {
            toast({ content: '必须上传附件', color: 'danger' });
            return false;
        }
    }
    return true;
}

export { isUploadedAttachments };

function isJSON(str) {
    if (typeof str == 'string') {
        try {
            JSON.parse(str);
            return true;
        } catch (e) {
            return false;
        }
    }
}

function adptBodyData(headRows = [], bodysData = {}) {
    headRows.map(row => {
        for (let key in row.values) {
            if (row.values[key].value || row.values[key].value == 0) {
                row.values[key].value += '';
            }
        }
        return row;
    });

    window.presetVar.bodys.forEach(bodyCode => {
        bodysData[bodyCode].rows.map(row => {
            for (let key in row.values) {
                if (row.values[key].value || row.values[key].value == 0) {
                    row.values[key].value += '';
                }
            }
            return row;
        });
    });
}

function filterAllRefParm(item, props, moduleid) {
    let PublicDefaultRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.PublicDefaultRefSqlBuilder'; //公共
    let OrgTreeRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder'; //组织
    let BusinessUnitTreeRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.BusinessUnitTreeRefSqlBuilder'; //组织
    let DeptTreeRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.DeptTreeRefSqlBuilder'; //部门
    let CurrtypeRefSqlFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.CurrtypeRefSqlBuilder'; //币种
    let PsndocClassFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.PsndocClassTreeGridRef'; //人员
    let PsndocTreeFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.PsndocTreeGridRef'; //人员
    let SupplierClassTreeRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.SupplierClassTreeRefSqlBuilder'; //供应商
    let CustClassDefaultTreeRefFilterPath = 'nccloud.web.erm.action.ref.sqlbuilder.CustClassDefaultTreeRefSqlBuilder'; //客户
    const CustomerVersionTreeGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.CustomerVersionTreeGridRef';
    const SupplierVersionGridRef = 'nccloud.web.erm.action.ref.sqlbuilder.SupplierVersionTreeGridRef';

    //所属组织，待确定是否需要特殊处理
    if (item.attrcode == 'pk_org') {
        item.queryCondition = () => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用编码再取一下外层
            if (!paramurl.c) {
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            const pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;
            return {
                pk_group:
                    moduleid == presetVar.head.head1
                        ? pk_group
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_group') || pk_group,
                TreeRefActionExt: OrgTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y',
                appcode: paramurl.c
            }; // 根据pk_group过滤
        };
    }

    if (item.attrcode == 'pk_org_v') {
        item.queryCondition = () => {
            let paramurl = getRequest1(parent.window.location.hash);
            //如果没取到应用编码再取一下外层
            if (!paramurl.c) {
                paramurl = getRequest1(parent.parent.window.location.hash);
            }
            const pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;
            return {
                pk_group:
                    moduleid == presetVar.head.head1
                        ? pk_group
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_group') || pk_group,
                TreeRefActionExt: OrgTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y',
                appcode: paramurl.c,
                isVerison: 'Y'
            }; // 根据pk_group过滤
        };
    }

    // 实际出行人改为多选
    if (item.attrcode === 'actualpedestrian') {
        item.isMultiSelectedEnabled = true;
    }

    //申请单位
    if (item.attrcode == 'apply_org') {
        item.queryCondition = () => {
            const pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;
            return {
                pk_group:
                    moduleid == presetVar.head.head1
                        ? pk_group
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_group') || pk_group,
                TreeRefActionExt: BusinessUnitTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_group过滤
        };
    }
    //承担单位
    if (item.attrcode == 'assume_org') {
        item.queryCondition = () => {
            const pk_group = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_group'].value;
            return {
                pk_group:
                    moduleid == presetVar.head.head1
                        ? pk_group
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_group') || pk_group,
                TreeRefActionExt: BusinessUnitTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_group过滤
        };
    }
    //申请部门
    if (item.attrcode == 'apply_dept') {
        item.queryCondition = () => {
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['apply_org'].value;
            return {
                pk_org: data,
                TreeRefActionExt: DeptTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据apply_org过滤
        };
    }
    //承担部门
    if (item.attrcode == 'assume_dept') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'assume_org') || pk_org,
                TreeRefActionExt: DeptTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据assume_org过滤
        };
    }
    //收支项目
    if (item.attrcode == 'pk_iobsclass') {
        item.queryGridUrl = window.location.origin + '/nccloud/uapbd/ref/InoutBusiClassTreeRef.do';
        item.queryCondition = () => {
            const apply_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['apply_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? apply_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'assume_org') || apply_org,
                TreeRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据assume_org过滤
        };
    }

    //供应商
    if (item.attrcode == 'pk_supplier') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                GridRefActionExt: SupplierClassTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_org过滤
        };
    }

    //客户
    if (item.attrcode == 'pk_customer') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                GridRefActionExt: CustClassDefaultTreeRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_org过滤
        };
    }
    //供应商版本
    if (item.attrcode == 'pk_supplier_v') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['billdate'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                queryDate: date,
                GridRefActionExt: SupplierVersionGridRef,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_org过滤
        };
    }

    //客户版本
    if (item.attrcode == 'pk_customer_v') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['billdate'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                queryDate: date,
                GridRefActionExt: CustomerVersionTreeGridRef,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_org过滤
        };
    }
    //供应商版本
    if (item.attrcode == 'pk_supplier_v') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['billdate'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                queryDate: date,
                GridRefActionExt: SupplierVersionGridRef,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_org过滤
        };
    }

    //客户版本
    if (item.attrcode == 'pk_customer_v') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            let date = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['billdate'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                queryDate: date,
                GridRefActionExt: CustomerVersionTreeGridRef,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据pk_org过滤
        };
    }

    //币种
    if (item.attrcode == 'pk_currtype') {
        item.queryCondition = () => {
            return {
                GridRefActionExt: CurrtypeRefSqlFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }

    //人员
    if (item.attrcode == 'pk_salesman' || item.attrcode == 'closeman' || item.attrcode == 'billmaker') {
        item.queryCondition = head => {
            const org_string = item.attrcode == 'pk_salesman' ? 'assume_org' : 'apply_org';
            /**
             * 业务员字段特殊处理，通过apply_org取不到值，需要通过assume_org字段取值
             * 为和表头申请人&申请单位一致，判断是否要穿pk_dept
             */
            const formValues = props.form.getAllFormValue(presetVar.head.head1);
            const orgKey = item.attrcode == 'pk_salesman' ? 'assume_org' : 'apply_org';
            const pk_org = _.get(formValues, `rows[0].values[${orgKey}].value`, '');
            const pk_dept = _.get(formValues, 'rows[0].values.apply_dept.value.', '');

            return {
                org_id:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, orgKey) || pk_org,
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, orgKey) || pk_org,
                pk_dept:
                    item.attrcode == 'pk_salesman'
                        ? ''
                        : moduleid == presetVar.head.head1
                        ? pk_dept
                        : getBodyValueBeforeRefRequest(props, moduleid, 'apply_dept') || pk_dept,
                GridRefActionExt: PsndocTreeFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据assume_org过滤
        };
    }

    //人员 增加代理申请处理
    if (item.attrcode == 'billmaker') {
        item.queryCondition = () => {
            const apply_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['apply_org'].value;
            let data_org =
                moduleid == presetVar.head.head1
                    ? apply_org
                    : getBodyValueBeforeRefRequest(props, moduleid, 'apply_org') || apply_org;

            return {
                tradetype: window.presetVar.billtype,
                org_id: data_org,
                pk_org: data_org,
                GridRefActionExt: PsndocTreeFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据assume_org过滤
        };
    }

    //项目
    if (item.attrcode == 'pk_project' || item.attrcode == 'jobid') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                GridRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }
    //项目任务
    if (item.attrcode == 'pk_wbs') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                TreeRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }
    //产品线
    if (item.attrcode == 'pk_proline') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                GridRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }
    //品牌
    if (item.attrcode == 'pk_brand') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                GridRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }

    //核算要素
    if (item.attrcode == 'pk_checkele') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                TreeRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }
    //利润中心
    if (item.attrcode == 'pk_pcorg') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                TreeRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }
    //成本中心
    if (item.attrcode == 'pk_resacostcenter') {
        item.queryCondition = () => {
            const pk_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            return {
                pk_org:
                    moduleid == presetVar.head.head1
                        ? pk_org
                        : getBodyValueBeforeRefRequest(props, moduleid, 'pk_org') || pk_org,
                TreeRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            };
        };
    }
    //报销事由
    if (item.attrcode == 'reason') {
        // 设置可以手工录入
        item.checkStrictly = false;
        item.queryCondition = () => {
            let data = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['apply_org'].value;

            return {
                pk_org: data,
                TreeRefActionExt: PublicDefaultRefFilterPath,
                DataPowerOperationCode: 'fi',
                /**使用权组**/ isDataPowerEnable: 'Y'
            }; // 根据assume_org过滤
        };
    }

    //处理交叉校验规则
    if (item.itemtype == 'refer') {
        let oldQueryCondition = item.queryCondition;
        let crossrule_itemkey = item.attrcode;
        item.queryCondition = obj => {
            let crossrule_datasout = props.createExtCardData(
                props.meta.getMeta().code,
                presetVar.head.head1,
                presetVar.bodys
            );
            let crossrule_tradetype = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_tradetype']
                .value;
            let crossrule_org = props.form.getAllFormValue(presetVar.head.head1).rows[0].values['pk_org'].value;
            let crossrule_datatypes = 'billcard';
            let crossrule_datas = crossrule_datasout;
            let isHead = moduleid == presetVar.head.head1 ? 'true' : 'false';
            if (window.presetVar.bodyChangeValuesAll != null && window.presetVar.bodyChangeValuesAll.rowid) {
                if (window.presetVar.bodyChangeValuesAll) {
                    crossrule_datas.body[presetVar.body.body1].rows = [window.presetVar.bodyChangeValuesAll];
                }
            }

            let conditionFlag = true;
            if (oldQueryCondition == null || oldQueryCondition == undefined || oldQueryCondition == 'undefined') {
                conditionFlag = false;
            }
            let oldData = '';
            if (conditionFlag) {
                oldData = oldQueryCondition();
            }
            if (oldData == null || oldData == undefined || oldData == 'undefined') {
                oldData = '';
            }
            let config = {
                crossrule_datas: JSON.stringify(crossrule_datas),
                crossrule_tradetype: crossrule_tradetype,
                crossrule_org: crossrule_org,
                crossrule_datatypes: crossrule_datatypes,
                crossrule_area: moduleid,
                crossrule_itemkey: crossrule_itemkey,
                crossrule_isHead: isHead,
                ...oldData
            };

            //参照类型的自定义项字段增加组织过滤
            //实际出行人是友报账特殊增加的字段，需要特殊处理
            if (
                !oldData.pk_org &&
                obj &&
                obj.attrcode &&
                (obj.attrcode.startsWith('defitem') || obj.datatype == '56' || obj.attrcode === 'actualpedestrian')
            ) {
                config.pk_org = crossrule_org;
            }

            if (obj == undefined || obj == null || obj.refType == undefined || obj.refType == null) {
                if (
                    config.TreeRefActionExt == null ||
                    config.TreeRefActionExt == undefined ||
                    config.TreeRefActionExt.length == 0
                ) {
                    config.TreeRefActionExt = PublicDefaultRefFilterPath;
                }
                return config;
            }

            if (obj.refType == 'grid') {
                if (
                    config.GridRefActionExt == null ||
                    config.GridRefActionExt == undefined ||
                    config.GridRefActionExt.length == 0
                ) {
                    config.GridRefActionExt = PublicDefaultRefFilterPath;
                }
            } else if (obj.refType == 'tree') {
                if (
                    config.TreeRefActionExt == null ||
                    config.TreeRefActionExt == undefined ||
                    config.TreeRefActionExt.length == 0
                ) {
                    config.TreeRefActionExt = PublicDefaultRefFilterPath;
                }
            } else if (obj.refType == 'gridTree') {
                if (
                    config.GridRefActionExt == null ||
                    config.GridRefActionExt == undefined ||
                    config.GridRefActionExt.length == 0
                ) {
                    config.GridRefActionExt = PublicDefaultRefFilterPath;
                }
            }

            return config;
        };
    }
}

function handleLoadDataResDada(meta, data) {
    if (data.data.body[presetVar.body.body1].rows[0]) {
        let bodyValues = data.data.body[presetVar.body.body1].rows[0].values;
        for (let attrcode in bodyValues) {
            meta[presetVar.body.body1].items.forEach(item => {
                if (item.attrcode == attrcode) {
                    item.initialvalue = {
                        value: bodyValues[attrcode].value,
                        display: (bodyValues[attrcode].display = null
                            ? bodyValues[attrcode].value
                            : bodyValues[attrcode].display)
                    };
                    //处理交叉校验规则和参照过滤
                    //filterAllRefParm(item,bodyValues);
                }
            });
        }
    }

    if (data.data.head[presetVar.head.head1].rows[0]) {
        let headValues = data.data.head[presetVar.head.head1].rows[0].values;
        for (let attrcode in headValues) {
            meta[presetVar.head.head1].items.forEach(item => {
                if (item.attrcode == attrcode) {
                    item.initialvalue = {
                        value: headValues[attrcode].value,
                        scale: headValues[attrcode].scale,
                        display: (headValues[attrcode].display = null
                            ? headValues[attrcode].value
                            : headValues[attrcode].display)
                    };
                    //处理交叉校验规则和参照过滤
                    //filterAllRefParm(item,headValues);
                }
            });
        }
    }
}

function genReqParamForLoadData(meta) {
    return getDefDataFromMeta(meta, '', null, null, 'head');
}
export default requestApiOverwrite;

// 1903方式，参数列表在url中，改为根据url的page属性从session中获取
// function getRequest1(url) {
//     if (!url)
//         url = document.location.search;
//     var theRequest = new Object();
//     if (url.indexOf("?") != -1) {
//         var str = url.substring(url.indexOf("?") + 1);
//         var strs = str.split("&");
//         for (var i = 0; i < strs.length; i++) {
//             theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
//         }
//     }
//     return theRequest;
// }
// xuzd5 适配到1909
function getRequest1(url) {
    if (!url) url = document.location.search;
    let sessionInfo = '';
    if (url.indexOf('page=') != -1) {
        //获取url中页面page参数 1909url中参数仅有page
        var page;
        if (url.indexOf('?') != -1) {
            var str = url.substring(url.indexOf('?') + 1);
            var strs = str.split('&');
            page = strs[0].split('=')[1];
        }

        //根据page获取session storage中原来1903url中的参数
        var msg = getGlobalStorage('sessionStorage', 'NCCAPPURL');
        msg = JSON.parse(msg);
        sessionInfo = msg[page];
    } else if (url.indexOf('?') != -1) {
        sessionInfo = url.substring(url.indexOf('?') + 1);
    } else {
        sessionInfo = url;
    }

    //解析参数
    var theRequest = new Object();
    var strs = sessionInfo.split('&');
    for (var i = 0; i < strs.length; i++) {
        theRequest[strs[i].split('=')[0]] = unescape(strs[i].split('=')[1]);
    }
    return theRequest;
}

/**
 * @description 无金额申请,过滤掉head和mtapp_detail中的orig_amount字段
 * @param {*} meta
 */
function filterOrigAmount(meta) {
    const filterKeys = ['pk_currtype', 'org_currinfo', 'orig_amount', 'group_currinfo', 'zzhllx', 'zzhllyrq'];
    const filterKeys1 = ['pk_currtype', 'org_currinfo', 'orig_amount', 'group_currinfo', 'zzhllx', 'zzhllyrq', 'opr'];
    meta.head.items = meta.head.items.filter(item => !filterKeys.includes(item.attrcode));
    meta.mtapp_detail.items = meta.mtapp_detail.items.filter(item => !filterKeys.includes(item.attrcode));
    meta.childform2.items = meta.mtapp_detail.items.filter(item => !filterKeys1.includes(item.attrcode));
    return meta;
}

export { filterOrigAmount };

/**
 * 表体参照请求前获取表体行某字段的值
 * @param {} props
 */
function getBodyValueBeforeRefRequest(props, moduleid, key) {
    let clickRow = props.cardTable.getClickRowIndex(moduleid);
    if (clickRow) {
        return _.get(clickRow, `record.values[${key}].value`, '');
    }
    let currentIndex = props.cardTable.getCurrentIndex(moduleid);
    if (currentIndex >= 0) {
        return _.get(props.cardTable.getDataByIndex(moduleid, currentIndex), `values[${key}].value`, '');
    }
    return '';
}
